package org.alex.sample.dao.Impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.alex.sample.VO.SubjectVO;
import org.alex.sample.VO.UserVO;
import org.alex.sample.dao.IUserDAO;
import org.alex.sample.model.ExamScore;
import org.alex.sample.model.ExamUserRole;
import org.alex.sample.model.ExamUserSubject;
import org.alex.sample.model.User;
import org.alex.sample.page.PagerModel;
import org.alex.sample.page.SystemContext;
import org.hibernate.SQLQuery;
import org.hibernate.transform.AliasToBeanResultTransformer;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sun.org.apache.xalan.internal.xsltc.compiler.util.StringType;

@Transactional
@Repository
public class IUserDAOImpl extends BaseHibernateDAO<User> implements IUserDAO{
	
	@Override
	public List<User> findAllUser() throws Exception {
		String hql = "FROM User";
		List<User> userList = this.find(hql);
		return userList;
	}
	
	@Override
	public void createUser(User user) throws Exception {
		this.save(user);
		Integer id = (Integer) this.createSqlQuery("select id from exam_user where user_name='" + user.getUserName() + "'")
				.addScalar("id", StandardBasicTypes.INTEGER).uniqueResult();
		String sql = "insert into exam_user_role(user_id,role_id) value(" + id + ",1)";
		this.createSqlQuery(String.valueOf(sql)).executeUpdate();
		
	}

	@Override
	public User findUserById(Integer id) throws Exception {
		User user = this.get(id);
		return user;
	}

	@Override
	public void editUser(User user) throws Exception {
		this.update(user);
	}

	@Override
	public void deleteUser(Integer id) throws Exception {
		this.deleteByKey(id);
	}

	@Override
	public Iterator<User> iterate(String queryString, Object[] values) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public PagerModel<UserVO> findAllByPage() throws Exception{
		PagerModel<UserVO> page = new PagerModel<UserVO>();
		ArrayList<UserVO> dates = new ArrayList<UserVO>();
		int offset = SystemContext.getOffset(); //偏移量
		int pageSize = SystemContext.getPageSize(); //每页的记录数
		
		//使用hibernate完成分页
		List<User> tempDates = (List<User>) this.getSession().createQuery("from User")
				.setFirstResult(offset).setMaxResults(pageSize).list();
		for(User user:tempDates) {
			UserVO userVO = new UserVO();
			BeanUtils.copyProperties(user, userVO);
			userVO.setGender(user.getGender().equals("0")?"男":"女");
			for(ExamUserRole examUserRole:user.getExamUserRole()) {
				userVO.setRoleName(examUserRole.getExamRole().getName());
				userVO.setRoleId(examUserRole.getExamRole().getRoleId());
			}
			List<SubjectVO> subjectVOList = new ArrayList<SubjectVO>();
			for(ExamUserSubject examUserSubject:user.getExamUserSubject()) {
				SubjectVO subjectVO = new SubjectVO();
				BeanUtils.copyProperties(examUserSubject.getSubject(), subjectVO);
				for(ExamScore examScore : subjectVO.getExamScore()) {
					if(user.getId() == examScore.getUser().getId() && subjectVO.getSubId() == examScore.getSubject().getSubId()) {
						subjectVO.setScoreId(examScore.getScoreId());
						subjectVO.setScoreExamTime(examScore.getExamTime());
						subjectVO.setScore(examScore.getScore());
					}
				}
				subjectVOList.add(subjectVO);
			}
			userVO.setSubjectVOList(subjectVOList);
			dates.add(userVO);
		}
		page.setDates(dates);
		page.setOffset(offset);
		page.setPageSize(pageSize);
		
		//获取总记录数
		long totalSize = (long)this.getSession().createQuery("select count(*) from User").uniqueResult();
		page.setTotalSize(totalSize);
		return page;
	}

	@Override
	public void saveStudentByExcel(List<User> userList) throws Exception {
		this.save(userList);
		for(User u : userList){
			Integer id = (Integer) this.createSqlQuery("select id from exam_user where user_name='" + u.getUserName() + "'")
					.addScalar("id", StandardBasicTypes.INTEGER).uniqueResult();
			String sql = "insert into exam_user_role(user_id,role_id) value(" + id + ",1)";
			this.createSqlQuery(String.valueOf(sql)).executeUpdate();
		}
	}

	//批量删除
	@Override
	public void deleteMoreUser(int[] idArr) throws Exception {
		List<User> userList = new ArrayList<User>();
		for(int i = 0; i < idArr.length; i++) {
			User user = this.get(idArr[i]);
			userList.add(user);
		}
		this.deleteAll(userList);
	}
	
}
